<?php


namespace app\admin\controller;

use app\admin\model\ComponentExceptionInfoRe;
use app\admin\model\ComponentExceptionLogging;
use app\BaseController;


use think\cache\driver\Redis;
use think\Db;
use think\facade\Cache;
use think\facade\Queue;
use think\facade\View;

class Test extends BaseController
{
    public function index()
    {

//        //todo 队列执行之前,的钩子
//
//
//        $data = [
//            'm' => 'app\admin\Job\Test',
//            'a' => 'doWork',
//            'param' => [
//                'name' => '瓦尔纳',
//                'work' => 'up'
//            ]
//        ];
//        $result = Queue::push('DailyTasks',  $data, 'queueDailyTasks');
//
//        return json(['msg' =>$result]);
        return View::fetch();
    }

    public function test()
    {
//        添加异常信息记录
        $this->addExceptionLogging();
        echo '成功';die;


        $projects_name = '剑圣六眼面具';
        $order_result['name'] = '订单xxx';
        $compp_result['drawing_name'] = '图名xxx1';
        $compp_result['drawing_no'] = '图好xxx1';
        $reset_num = 10;
        $repair_num = 20;
        $id = 12;
        $domain = get_config_cache('domain')['admin_domain'].'/admin/compExcep/creaCompInfo?id='.$id;

        $html =
            <<<HTML
项目名称：$projects_name 项目订单名称：$order_result[name] 部件图名：$compp_result[drawing_name] 部件图号：$compp_result[drawing_no] <br/>
异常信息：重置数量：$reset_num, 修复数量：$repair_num <br/>
根据异常信息中的数量，生成各自重置或修复数量的生产信息，信息中会标识类型重置或修复。如上信息，会生成一条新的部件信息，数量：$reset_num ，异常类型：重置的部件信息；数量：$repair_num ，异常类型：修复的部件信息。<br/>
<a target=“_blank” href="$domain"> 根据异常信息一键生成生产信息</a>
HTML;
        echo $html;die;


        gateway_to_group(1, ['data'=>'你好呀']);die;

        $host='127.0.0.1';
        $user='root';
        $password='root';
        $dbName='szcj1';
        $link=mysqli_connect($host,$user,$password,$dbName);
        $res = mysqli_query($link,'select * from xx_test where id=16');

        $content = mysqli_fetch_array($res)['content'];
        $content = json_decode($content, true);
        dump($content);
        $gateway = (new \GatewayClient\Gateway);
        $gateway::$registerAddress = '127.0.0.1:1238';
        $result = $gateway::sendToGroup('szcj_group_1', json_encode(['data'=>'你好呀']));
        dump($result);
//        $result = \GatewayClient\Gateway::sendToClient('7f0000010b540000000b', json_encode(['data'=>'你好呀']));
        dump($result);die;
        return View::fetch('test');
    }


    public function bind()
    {
        $input = input();
        if(!empty($input)){

        }
        return json();
    }


    public function queueNotice()
    {
        //测试
        //订单投入生产消息（系统消息）
        $notice_data = [
            'type' => 'system',
            'to_user_id'   => 0,
            'from_user_id'   => 2,
            'content' => [
                'data' => 'xxx订单以投入生产'
            ]
        ];


        event('SendNotice', $notice_data);
    }

    /**
     * Desc: 添加异常信息记录
     * User: 苏鹏
     * Date: 2023/11/10
     * Time: 13:37
     * @return void
     */
    public function addExceptionLogging()
    {
        try{
            $comp_exce_logg_m = new ComponentExceptionLogging();
            $comp_exce_logg_m->startTrans();
            $data = [
                'reason' => '切割中刀片使用寿命结束，需要申请重置',
                'component_id' => 3, //部件id
                'number' => 5, //需要重置或修复的数量
            ];

            //保存异常申请记录
            $comp_exce_logg_m->insert($data);
            //将信息同步至异常信息关联表
            $component_m = new \app\admin\model\Component();
//            父类id存在 一直执行 查询所有父类id
            $pid = $component_m->where('id', '=', $data['component_id'])->where('status', '=', 1)->value('pid');
            $pid_array[] = $pid;
            $exception_info_array[] = [
                'model' =>  'Component',
                'is_main' => 1,
                'model_id' => $data['component_id'],
                'content' => ''
            ];

            $component_id = $data['component_id'];
            while (!empty($component_id))
            {
                $component_id = $component_m->where('id', '=', $component_id)->where('status', '=', 1)->value('pid');
                if(!empty($component_id))
                {
                    $pid_array[] = $pid;
                    $exception_info_array[] = [
                        'model' =>  'Component',
                        'is_main' => 2,
                        'model_id' => $pid,
                        'content' => ''
                    ];
                }
            }
            //异常信息关联订单id
            $projects_order_id =$component_m->where('id', '=', $data['component_id'])->where('status', '=', 1)->value('projects_order_id');
            $exception_info_array[] = [
                'model' =>  'ProjectsOrder',
                'is_main' => 2,
                'model_id' => intval($projects_order_id),
                'content' => ''
            ];
            //保存异常信息与部件的关联关系
            $comp_exce_info_re = new \app\admin\model\ComponentExceptionInfoRe();
            //不存在才会添加
            $new_exception_info_array = [];
            foreach($exception_info_array as $k=>$v)
            {
                $id_exist = $comp_exce_info_re->where('model', '=', $v['model'])
                    ->where('model_id', '=', $v['model_id'])
                    ->where('is_main', '=', $v['is_main'])
                    ->value('id');
                if(empty($id_exist))
                {
                    $new_exception_info_array[] = $v;
                }
            }
            if(!empty($new_exception_info_array))
            {
                $comp_exce_info_re->saveAll($new_exception_info_array);
            }

            $comp_exce_logg_m->commit();
        }catch (\Exception $e){
            $comp_exce_logg_m->rollback();
            return re_error_json($e->getMessage());
        }
        return re_success_json();
    }


}